import type {
  BrowsingHistory,
  BrowsingHistorySearchOptions,
  DatabaseResult,
  QueryBrowsingHistoryParams
} from '~types/browsing-history'
import { reactive, ref } from 'vue'

// 类型别名
type HistoryItem = BrowsingHistory
type QueryParams = QueryBrowsingHistoryParams

/**
 * 历史记录数据管理 Composable
 */
export function useHistoryData() {
  // 响应式数据
  const historyItems = ref<HistoryItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 分页状态
  const pagination = reactive({
    page: 1,
    itemsPerPage: 50, // 每页加载50条记录
    hasMore: true
  })

  const isLoadingMore = ref(false)
  const isRefreshing = ref(false)
  const totalCount = ref(0)

  /**
   * 加载历史记录
   */
  const loadHistory = async (params?: QueryParams) => {
    loading.value = true
    error.value = null

    try {
      const queryParams: QueryParams = {
        limit: pagination.itemsPerPage,
        offset: (pagination.page - 1) * pagination.itemsPerPage,
        order_by: 'visit_time',
        order_direction: 'DESC',
        ...params
      }

      const result: DatabaseResult<HistoryItem[]> =
        await _pre_.browsingHistory.queryRecords(queryParams)

      if (result.success && result.data) {
        if (pagination.page === 1) {
          historyItems.value = result.data
        } else {
          historyItems.value.push(...result.data)
        }

        // 检查是否还有更多数据
        pagination.hasMore = result.data.length === pagination.itemsPerPage
      } else {
        throw new Error(result.error || '加载历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '未知错误'
      console.error('加载历史记录失败:', error_)
    } finally {
      loading.value = false
    }
  }

  /**
   * 加载更多历史记录
   */
  const loadMore = async (params?: QueryParams) => {
    if (!pagination.hasMore || loading.value || isLoadingMore.value) return

    isLoadingMore.value = true

    try {
      pagination.page++

      const queryParams: QueryParams = {
        limit: pagination.itemsPerPage,
        offset: (pagination.page - 1) * pagination.itemsPerPage,
        order_by: 'visit_time',
        order_direction: 'DESC',
        ...params
      }

      const result: DatabaseResult<HistoryItem[]> =
        await _pre_.browsingHistory.queryRecords(queryParams)

      if (result.success && result.data) {
        // 避免重复数据
        const existingIds = new Set(historyItems.value.map(item => item.id))
        const newItems = result.data.filter(item => !existingIds.has(item.id))

        historyItems.value.push(...newItems)
        totalCount.value = historyItems.value.length

        // 检查是否还有更多数据
        pagination.hasMore = result.data.length === pagination.itemsPerPage

        console.log(`加载更多：新增 ${newItems.length} 条记录，总计 ${totalCount.value} 条`)
      } else {
        throw new Error(result.error || '加载更多历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '加载更多失败'
      console.error('加载更多历史记录失败:', error_)
    } finally {
      isLoadingMore.value = false
    }
  }

  /**
   * 刷新历史记录
   */
  const refresh = async (params?: QueryParams) => {
    if (isRefreshing.value) return

    isRefreshing.value = true

    try {
      // 重置分页状态
      pagination.page = 1
      pagination.hasMore = true

      const queryParams: QueryParams = {
        limit: pagination.itemsPerPage,
        offset: 0,
        order_by: 'visit_time',
        order_direction: 'DESC',
        ...params
      }

      const result: DatabaseResult<HistoryItem[]> =
        await _pre_.browsingHistory.queryRecords(queryParams)

      if (result.success && result.data) {
        historyItems.value = result.data
        totalCount.value = result.data.length
        pagination.hasMore = result.data.length === pagination.itemsPerPage

        console.log(`刷新完成：加载 ${result.data.length} 条记录`)
      } else {
        throw new Error(result.error || '刷新历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '刷新失败'
      console.error('刷新历史记录失败:', error_)
    } finally {
      isRefreshing.value = false
    }
  }

  /**
   * 搜索历史记录
   */
  const searchHistory = async (query: string, options?: BrowsingHistorySearchOptions) => {
    loading.value = true
    error.value = null

    try {
      const searchOptions = {
        limit: pagination.itemsPerPage,
        searchInUrl: true,
        searchInTitle: true,
        ...options
      }

      const result: DatabaseResult<HistoryItem[]> = await _pre_.browsingHistory.search(
        query,
        searchOptions
      )

      if (result.success && result.data) {
        historyItems.value = result.data
        pagination.page = 1
        pagination.hasMore = result.data.length === pagination.itemsPerPage
      } else {
        throw new Error(result.error || '搜索历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '未知错误'
      console.error('搜索历史记录失败:', error_)
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除历史记录项
   */
  const deleteHistoryItems = async (itemIds: number[]) => {
    loading.value = true
    error.value = null

    try {
      // 确保传递给主进程的是纯数组，避免Vue响应式对象序列化问题
      const plainItemIds = [...itemIds]

      // 批量删除
      const result: DatabaseResult<void> = await _pre_.browsingHistory.deleteRecords(plainItemIds)

      if (result.success) {
        // 从本地数据中移除已删除的项
        historyItems.value = historyItems.value.filter(
          item => item.id !== undefined && !itemIds.includes(item.id)
        )
        console.log(`成功删除 ${itemIds.length} 条历史记录`)
      } else {
        throw new Error(result.error || '删除历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '未知错误'
      console.error('删除历史记录失败:', error_)
      throw error_ // 重新抛出错误以便上层处理
    } finally {
      loading.value = false
    }
  }

  /**
   * 清空所有历史记录
   */
  const clearAllHistory = async () => {
    loading.value = true
    error.value = null

    try {
      const result: DatabaseResult<void> = await _pre_.browsingHistory.clearAllRecords()

      if (result.success) {
        historyItems.value = []
        totalCount.value = 0
        pagination.page = 1
        pagination.hasMore = false
        console.log('成功清空所有历史记录')
      } else {
        throw new Error(result.error || '清空历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '未知错误'
      console.error('清空历史记录失败:', error_)
      throw error_
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取历史记录总数
   */
  const getRecordCount = async () => {
    try {
      const result: DatabaseResult<number> = await _pre_.browsingHistory.getRecordCount()

      if (result.success && typeof result.data === 'number') {
        totalCount.value = result.data
      } else {
        throw new Error(result.error || '获取记录总数失败')
      }
    } catch (error_) {
      console.error('获取记录总数失败:', error_)
    }
  }

  /**
   * 获取今天的历史记录
   */
  const getTodayHistory = async () => {
    loading.value = true
    error.value = null

    try {
      const result: DatabaseResult<HistoryItem[]> = await _pre_.browsingHistory.getTodayRecords(200)

      if (result.success && result.data) {
        historyItems.value = result.data
        pagination.page = 1
        pagination.hasMore = false
      } else {
        throw new Error(result.error || '获取今天的历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '未知错误'
      console.error('获取今天的历史记录失败:', error_)
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取本周的历史记录
   */
  const getThisWeekHistory = async () => {
    loading.value = true
    error.value = null

    try {
      const result: DatabaseResult<HistoryItem[]> =
        await _pre_.browsingHistory.getThisWeekRecords(500)

      if (result.success && result.data) {
        historyItems.value = result.data
        pagination.page = 1
        pagination.hasMore = false
      } else {
        throw new Error(result.error || '获取本周的历史记录失败')
      }
    } catch (error_) {
      error.value = error_ instanceof Error ? error_.message : '未知错误'
      console.error('获取本周的历史记录失败:', error_)
    } finally {
      loading.value = false
    }
  }

  /**
   * 重置数据
   */
  const resetData = () => {
    historyItems.value = []
    error.value = null
    totalCount.value = 0
    pagination.page = 1
    pagination.hasMore = true
  }

  return {
    // 响应式数据
    historyItems,
    loading,
    error,
    totalCount,
    pagination,
    isLoadingMore,
    isRefreshing,

    // 方法
    loadHistory,
    loadMore,
    refresh,
    searchHistory,
    deleteHistoryItems,
    clearAllHistory,
    getRecordCount,
    getTodayHistory,
    getThisWeekHistory,
    resetData
  }
}
